package org.qloudgen.borg.security;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.qloudgen.borg.CommonValues;
import org.qloudgen.borg.beans.UserBean;
import org.qloudgen.borg.pages.common.BasePage;

@SuppressWarnings("rawtypes")
public class LoginPage extends BasePage{

	private static final long serialVersionUID = 1L;
	private PageParameters pm = new PageParameters() ;
	
	@SuppressWarnings("unchecked")
	public LoginPage(){
		
		super();
		
		Form form = new Form("form"){
			
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit() {
				UserBean user = (UserBean) getDefaultModelObject();
				pm.add("userNo", user.getUserNo());				
				login(user);
			}
		};
		
		form.setOutputMarkupId(true);
		form.setDefaultModel(new CompoundPropertyModel(new UserBean()));	
		add(form);

		TextField userNo = new TextField("userNo");
		form.add(userNo);
		
		form.add(new PasswordTextField("userPassword").setRequired(false));
		
		Button login = new Button("login") ;
		form.add(login);
		
	}

	protected void login(UserBean user) {
		
		DilithiumSession session = (DilithiumSession)getSession();
		int ret = session.login(user);
		
		if (ret == 0) { 			
//			continueToOriginalDestination();
			setResponsePage(getApplication().getHomePage(),pm);     
		} else if (ret == -1) {         
			error(CommonValues.ERROR_LOGIN);      
		} else if (ret == -2) {         
			error(CommonValues.ERROR_LOGIN_USER_PAUSED);    
		}
	}

}
